using System.Text;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Lazy.Captcha.Core;

namespace Lzfy_His_Service.Services
{
    public class LazyCaptchaService : ICaptchaService
    {
        private readonly IMemoryCache _cache;
        private readonly ILogger<LazyCaptchaService> _logger;
        private readonly ICaptcha _captcha;
        private const int ExpirationMinutes = 5;
        
        public LazyCaptchaService(IMemoryCache cache, ILogger<LazyCaptchaService> logger, ICaptcha captcha)
        {
            _cache = cache;
            _logger = logger;
            _captcha = captcha;
        }
        
        public Task<string> GenerateCaptchaAsync(string sessionId)
        {
            try
            {
                // 生成验证码
                var captchaData = _captcha.Generate(sessionId);
                
                // 将验证码存储到缓存中
                var cacheKey = $"captcha_{sessionId}";
                _cache.Set(cacheKey, captchaData.Code.ToUpper(), TimeSpan.FromMinutes(ExpirationMinutes));
                
                _logger.LogInformation($"Generated LazyCaptcha for session {sessionId}");
                
                // 确保返回完整的base64数据URI格式（包含data:image/png;base64,前缀）
                if (!string.IsNullOrEmpty(captchaData.Base64) && !captchaData.Base64.StartsWith("data:"))
                {
                    return Task.FromResult($"data:image/png;base64,{captchaData.Base64}");
                }
                
                return Task.FromResult(captchaData.Base64);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error generating LazyCaptcha for session {sessionId}");
                throw;
            }
        }
        
        public Task<byte[]> GenerateCaptchaImageBytesAsync(string sessionId)
        {
            try
            {
                // 生成验证码
                var captchaData = _captcha.Generate(sessionId);
                
                // 将验证码存储到缓存中
                var cacheKey = $"captcha_{sessionId}";
                _cache.Set(cacheKey, captchaData.Code.ToUpper(), TimeSpan.FromMinutes(ExpirationMinutes));
                
                // 将Base64转换为字节数组
                var base64Data = captchaData.Base64;
                if (base64Data.StartsWith("data:image/"))
                {
                    var commaIndex = base64Data.IndexOf(',');
                    if (commaIndex > 0)
                    {
                        base64Data = base64Data.Substring(commaIndex + 1);
                    }
                }
                
                var imageBytes = Convert.FromBase64String(base64Data);
                
                _logger.LogInformation($"Generated LazyCaptcha image bytes for session {sessionId}");
                return Task.FromResult(imageBytes);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error generating LazyCaptcha image bytes for session {sessionId}");
                throw;
            }
        }
        
        public Task<bool> ValidateCaptchaAsync(string sessionId, string captcha)
        {
            try
            {
                if (string.IsNullOrEmpty(sessionId) || string.IsNullOrEmpty(captcha))
                {
                    return Task.FromResult(false);
                }
                
                var cacheKey = $"captcha_{sessionId}";
                if (_cache.TryGetValue(cacheKey, out string? storedCaptcha))
                {
                    // 验证成功后立即删除验证码（防止重复使用）
                    _cache.Remove(cacheKey);
                    
                    var isValid = string.Equals(storedCaptcha, captcha.ToUpper(), StringComparison.OrdinalIgnoreCase);
                    _logger.LogInformation($"LazyCaptcha validation for session {sessionId}: {(isValid ? "Success" : "Failed")}");
                    return Task.FromResult(isValid);
                }
                
                _logger.LogWarning($"LazyCaptcha not found or expired for session {sessionId}");
                return Task.FromResult(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error validating LazyCaptcha for session {sessionId}");
                return Task.FromResult(false);
            }
        }
        
        public async Task ClearExpiredCaptchasAsync()
        {
            // MemoryCache 会自动清理过期项，这里可以添加额外的清理逻辑
            await Task.CompletedTask;
        }
    }
}